<?php
namespace Modules\Backstage\Controllers;

class TradeBusinessBuyController extends \Phalcon\Mvc\Controller {
	public function beforeExecuteRoute(\Phalcon\Mvc\Dispatcher $dispatcher) {
		$this -> response -> setStatusCode(200, 'OK') -> sendHeaders() -> setContentType('application/json', 'UTF-8');

		$service = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
		if($service['code'] != 0) {
			$this -> response -> setJsonContent(['code'=>-1,'msg'=>$service['message'] ]) -> send();
			exit;
		}

		$this -> account::getAclInstance() -> check($this, $dispatcher, $service['model'] -> roles_id);
	}


	public function indexAction() {
		$query = $this -> request -> getQuery();
		if(!isset($query['page'])) {
			$query['page'] = 1;
		} else if($query['page'] <= 0)  {
			$query['page'] = 1;
		} else {
			$query['page'] = abs($query['page']);
		}

		if(!isset($query['limit'])) {
			$query['limit'] = 10;
		} else if($query['limit'] <= 0)  {
			$query['limit'] = 10;
		} else {
			$query['limit'] = abs($query['limit']);
		}

		$service = $this -> tradeSecond::getBuyLogicInstance() -> pager([], $query['limit'], $query['page']);
		if($service['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$service['code'],'msg'=>$service['message']]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success', 'pager' => $service['pager']]);
	}

	public function matchIndexAction($id) {
		$findTradeBuy = $this -> trade::getBuyServiceInstance() -> findFirstById($id);
		if($findTradeBuy['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$findTradeBuy['code'],'msg'=>$findTradeBuy['message']]);
		}

		$query = $this -> request -> getQuery();
		if(!isset($query['page'])) {
			$query['page'] = 1;
		} else if($query['page'] <= 0)  {
			$query['page'] = 1;
		} else {
			$query['page'] = abs($query['page']);
		}

		if(!isset($query['limit'])) {
			$query['limit'] = 10;
		} else if($query['limit'] <= 0)  {
			$query['limit'] = 10;
		} else {
			$query['limit'] = abs($query['limit']);
		}

		$service = $this -> tradeSecond::getSellLogicInstance() -> match(['trade_buy' => $findTradeBuy['trade_buy']], $query['limit'], $query['page']);
		if($service['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$service['code'],'msg'=>$service['message']]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success', 'trade_buy' => $findTradeBuy['trade_buy'], 'pager' => $service['pager']]);
	}

	public function matchAction($id) {
		$post = $this -> request -> getPost();
		if(!isset($post['trade_sell_ids']) || empty($post['trade_sell_ids']) || !is_array($post['trade_sell_ids'])) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'请正确选择匹配订单!']);
		}

		$tradeSellIds = '';
		foreach($post['trade_sell_ids'] as $tradeSellId) {
			$tradeSellIds .= $tradeSellId . ',';
		}
		if(empty($tradeSellIds)) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'请正确选择匹配订单!']);
		}
		$tradeSellIds = rtrim($tradeSellIds, ',');

		$findFirstTradeBuy = $this -> trade::getBuyServiceInstance() -> findFirstById($id);
		if($findFirstTradeBuy['trade_buy'] -> status != 0) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'当前订单已匹配!']);
		}

		$findTradeSell = $this -> tradeSecond::getSellServiceInstance() -> find([
			'conditions' => 'status = 0 AND trade_sell_id in (' . $tradeSellIds . ')',
			'order' => 'status ASC, create_time ASC'
		]);
		if($findTradeSell['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'你选择的订单已经匹配!']);
		}

		$currentTime = time();
		$currentAmount = $findFirstTradeBuy['trade_buy'] -> amount;

		$this -> db -> begin();
		try {
			foreach($findTradeSell['trade_sell'] as $tradeSell) {
				if($currentAmount <= 0) {
					break;
				}
	
				if($tradeSell -> amount <= $currentAmount) {
					$currentAmount -= $tradeSell -> amount;

					$tradeSell -> to_user_id = $findFirstTradeBuy['trade_buy'] -> from_user_id;
					$tradeSell -> status = 2;
					$tradeSell -> last_time = $currentTime;

					$createTrade = $this -> tradeSecond::getBuyServiceInstance() -> create([
						'trade_sell_id' => $tradeSell -> trade_sell_id,
						'from_user_id' => $findFirstTradeBuy['trade_buy'] ->  from_user_id,
						'to_user_id' => $tradeSell -> from_user_id,
						'profit' => $findFirstTradeBuy['trade_buy'] -> profit,
						'amount' => $tradeSell -> amount,
						'original_amount' => $findFirstTradeBuy['trade_buy'] -> original_amount,
						'loop_number' => $findFirstTradeBuy['trade_buy'] -> loop_number,
						'create_time' => $currentTime,
						'last_time' => $currentTime,
						'status' => 1,
            'is_first' => $findFirstTradeBuy['trade_buy'] -> is_first
					]);
					$tradeSell -> trade_buy_id = $createTrade['trade_buy'] -> trade_buy_id;
					if($createTrade['code'] != 0) {
						throw new \Exception($createTrade['message']);
					}

					if(!$tradeSell -> save()) {
						throw new \Exception('订单匹配失败');
					}

					$findFirstUser = $this -> user::getServiceInstance() -> findFirstById($tradeSell -> from_user_id);
					if($findFirstUser['code'] == 0) {
						$this -> SMS::getServiceInstance() -> sendSMS(['t'=>2,'account' => $findFirstUser['user'] -> account,'create_time'=>$tradeSell->create_time,'mobile'=>$findFirstUser['user'] -> cellphone]);
					}
					
				}
			}

			if($currentAmount <= 0) {
				if(!$findFirstTradeBuy['trade_buy'] -> delete()) {
					throw new \Exception('订单匹配失败');
				}
			} else  if($findFirstTradeBuy['trade_buy'] -> amount != $currentAmount) {
				$findFirstTradeBuy['trade_buy'] -> amount = $currentAmount;
				if(!$findFirstTradeBuy['trade_buy'] -> save()) {
					throw new \Exception('订单匹配失败');
				}
			}

			$findFirstUser = $this -> user::getServiceInstance() -> findFirstById($findFirstTradeBuy['trade_buy'] -> from_user_id);
			if($findFirstUser['code'] == 0) {
				$this -> SMS::getServiceInstance() -> sendSMS(['t'=>1,'account' => $findFirstUser['user'] -> account,'create_time'=>$findFirstTradeBuy['trade_buy']->create_time,'mobile'=>$findFirstUser['user'] -> cellphone]);
			}

			$this -> db -> commit();
		} catch(\Exception $e) {
			$this -> db -> rollback();

			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>$e -> getMessage()]);
		}
		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'匹配成功']);
	}
}